package com.neuedu.corejava.ch12.homework;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyFileReader {

	public void copyAndFilter(String src, String desc) {
		
		if (src == null || desc == null) {
			return;
		}

		File srcFile  = new File(src);
		File descFile = new File(desc);

		if (!srcFile.exists()) {
			return;
		}
		
		FileReader reader = null;
		FileWriter writer = null; 
		BufferedReader bufferedReader = null;
		
		if (!descFile.exists()) {
			try {
				descFile.getParentFile().mkdirs();
				descFile.createNewFile();
				
				reader = new FileReader(srcFile);//节点流
				bufferedReader =new BufferedReader(reader);//处理流
				writer = new FileWriter(descFile);//节点流
				
				String data = null;
				//readLine一次读取一行内容，文件读取完毕返回null
				while((data=bufferedReader.readLine()) != null) {
			         String newData = data.replaceAll("l", "L");
			         writer.write(newData);
			        // writer.write("\r\n");
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if(writer != null) {
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(bufferedReader != null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}
		}

	}

	/**
	 * 把一段文本内容写入到一个指定的文件
	 * 
	 * @param fileName
	 * @param content
	 */

	public void writeFile(String fileName, String content) {
		if (fileName == null) {
			return;
		}

		File file = new File(fileName);
		FileOutputStream fileOutputStream = null;

		try {
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			// 文件的写入有两种模式：false--重写，true--追加
			fileOutputStream = new FileOutputStream(file, false);
			// 需要把字符串转换成字节数组，转换时需要注意可能产生乱码
			fileOutputStream.write(content.getBytes());

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public static void main(String[] args) {
		MyFileReader fReader = new MyFileReader();
		fReader.writeFile("c:\\test.txt", "Hello JAVA");
		System.out.println("文件新增成功");
		
		fReader.copyAndFilter("c:\\test.txt","c:\\test2.txt");
		
		
	}

}
